class DragScroll {
  constructor(container) {
    this.container = container;
    this.isDragging = false;
    this.startX = 0;
    this.scrollLeft = 0;

    this.container.addEventListener('mousedown', this.startDrag.bind(this));
    this.container.addEventListener('mousemove', this.drag.bind(this));
    this.container.addEventListener('mouseup', this.endDrag.bind(this));
    this.container.addEventListener('mouseleave', this.endDrag.bind(this));
    
    // 添加触摸事件支持
    this.container.addEventListener('touchstart', this.startDrag.bind(this));
    this.container.addEventListener('touchmove', this.drag.bind(this));
    this.container.addEventListener('touchend', this.endDrag.bind(this));
  }

  startDrag(e) {
    // 如果目标是图片，则不触发拖动
    if (e.target.tagName === 'IMG') {
      return;
    }
    
    this.isDragging = true;
    this.startX = (e.pageX || e.touches[0].pageX) - this.container.offsetLeft;
    this.scrollLeft = this.container.scrollLeft;
    this.container.style.cursor = 'grabbing';
    this.container.style.userSelect = 'none';
  }

  drag(e) {
    if (!this.isDragging) return;
    e.preventDefault();
    const x = (e.pageX || e.touches[0].pageX) - this.container.offsetLeft;
    const walk = (x - this.startX) * 2; // 乘以2增加拖动灵敏度
    this.container.scrollLeft = this.scrollLeft - walk;
  }

  endDrag() {
    this.isDragging = false;
    this.container.style.cursor = 'grab';
    this.container.style.removeProperty('user-select');
  }
}

// 初始化所有.card_box
document.querySelectorAll('.card_box').forEach(container => {
  new DragScroll(container);
});
